import Vue from 'vue'

export var f

export function getAttendanceState(item, timeToWork, timeToGo) {
  item.f_state = ''
  if(!item.f_signin_time || !item.f_knockoff_time)
    item.f_state = '缺勤'
  else {
    let signin_time = item.f_signin_time.substring(11, 16)
    let knockoff_time = item.f_knockoff_time.substring(11, 16)
    if(signin_time > timeToWork)
      item.f_state = '迟到'
    if(knockoff_time < timeToGo)
      item.f_state = item.f_state + '早退'
  }
  if(!item.f_state)
    item.f_state = '正常'
}

export function toStandardYearMonth() {
  let dt = new Date()
  let month = dt.getMonth()+ 1
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month)
}

export function toStandardDateString() {
  let dt = new Date()
  let month = dt.getMonth()+ 1
  let date = dt.getDate()
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month) + '-' + (date< 10? '0'+ date : date)
}

export function toStandardTimeString() {
  let dt = new Date()
  let month = dt.getMonth()+ 1
  let date = dt.getDate()
  let hour = dt.getHours()
  let min = dt.getMinutes()
  let sec = dt.getSeconds()
  return dt.getFullYear() + '-' + (month< 10? '0'+ month : month) + '-' + (date< 10? '0'+ date : date)
    + ' ' + (hour <10? '0'+ hour : hour) + ':' + (min<10? '0'+ min : min) + ':' + (sec< 10? '0'+ sec : sec)
}

export function to3339TimeString() {
  let dt = new Date()
  let month = dt.getMonth()+ 1
  let date = dt.getDate()
  let hour = dt.getHours()
  let min = dt.getMinutes()
  let sec = dt.getSeconds()
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month) + '-' + (date<10? '0'+ date : date)
    + 'T' + (hour<10? '0'+ hour : hour) + ':' + (min<10? '0'+ min : min) + ':' + (sec<10? '0'+ sec : sec)
}

export function parse3339String(strDate) {
  return new Date(
    strDate.substr(0, 4), strDate.substr(5, 2)-1, strDate.substr(8, 2)
    ,strDate.substr(11, 2), strDate.substr(14, 2), strDate.substr(17, 2)
  )
}

export function format3339TimeString(dt) {
  let month = dt.getMonth()+1
  let date = dt.getDate()
  let hour = dt.getHours()
  let min = dt.getMinutes()
  let sec = dt.getSeconds()
  return dt.getFullYear() + '-' + (month<10? '0'+ month : month) + '-' + (date<10? '0'+ date : date)
      + 'T' + (hour<10? '0'+ hour : hour) + ':' + (min<10? '0'+ min : min) + ':' + (sec<10? '0'+ sec : sec)
}

export function guid() {
  let buf = new Uint16Array(8)
  window.crypto.getRandomValues(buf)
  let S4 = function(num) {
      let ret = num.toString(16)
      while(ret.length < 4){
          ret = '0' + ret
      }
      return ret
  }
  return (S4(buf[0])+S4(buf[1])+S4(buf[2])+S4(buf[3])+S4(buf[4])+S4(buf[5])+S4(buf[6])+S4(buf[7]))
}

export function choices(role, param, hasBlank = false, blankHint='请选择') {
  if(role == 'view') {
    Vue.getParams(param, [null])
  } else {
    let result = []
    if(hasBlank)
      result.push({label: blankHint, value: null})
    if(!Vue.param || !Vue.param[param])
      result.push({label: '请在系统设置里更新参数', value: '请在系统设置里更新参数'})
    else {
      //console.log(param)
      //console.log(JSON.stringify(Vue.param))
      let p = Vue.param[param]
      p.forEach(function(item) {
        result.push({label: item.name, value: item.name})
      })
    }
    return result
  }
}

export function required(param) {
  if(typeof param === 'number' && param == 0)
    return false
  if(!param)
    return true
  param = param + ''
  param = param.trim()
  if(!param)
    return true
  return false
}

export function isInt(n){
  console.log('判断整数' + n)
  return !window.isNaN(n) && n % 1 === 0
}

export function isFloat(n){
  console.log('判断小数' + n)
  return !window.isNaN(n)
}

// this will convert all true/false to boolean
export function booleanFilter(paper) {
    for(let key in paper) {
      if(!paper.hasOwnProperty(key))
        continue
      if(typeof paper[key] == "object" && paper[key] != null) {
        booleanFilter(paper[key]);
      } else {
        if(paper[key] === "true" || paper[key] == "false")
          paper[key] = (paper[key] === "true")
      }
    }
}
// recursively traverse through each path
export function ratifyPics(paper) {
  for(let key in paper) {
    if(key.endsWith('_path')) {
      if(!paper[key]) {
        paper[key] = 'rs/db/file/nopic.png'
      } else {
        paper[key] = 'rs/db/file/' + paper[key]
      }
    } else if(paper[key] !== null && typeof(paper[key]) == "object") {
      ratifyPics(paper[key])
    }
  }
}

// 通过地址栏的参数获取参数内容
export function getUrlParames (param) {
  var query = window.location.search
  var iLen = param.length
  var iStart = query.indexOf(param)
  if (iStart === -1) {
    return ''
  }
  iStart += iLen + 1
  var iEnd = query.indexOf('&', iStart)
  if (iEnd === -1) {
    return query.substring(iStart)
  }
  return query.substring(iStart, iEnd)
}

// 从地址栏获取加密的参数
export function getUrlCompileParames (param) {
  var query = uncompileStr(window.location.search.slice(1, window.location.search.length))
  var iLen = param.length
  var iStart = query.indexOf(param)
  if (iStart === -1) {
    return ''
  }
  iStart += iLen + 1
  var iEnd = query.indexOf('&', iStart)
  if (iEnd === -1) {
    return query.substring(iStart)
  }
  return query.substring(iStart, iEnd)
}

// 对字符串进行加密
export function compileStr (code) {
  let c = String.fromCharCode(code.charCodeAt(0) + code.length)
  for (let i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1))
  }
  return escape(c)
}
// 字符串进行解密
export function uncompileStr (code) {
  code = unescape(code)
  let c = String.fromCharCode(code.charCodeAt(0) - code.length)
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1))
  }
  return c
}
// load script and other stuff
export function loadscript(type, fileName) {
  return new Promise((resolve, reject)=> {
    let element
    if(type == 'css') {
      element = document.createElement('link')
      element.setAttribute("rel", "stylesheet")
      element.setAttribute("type", "text/css")
      element.setAttribute("href", fileName)
    } else if(type == 'js') {
      element = document.createElement('script')
      element.setAttribute("type","text/javascript")
      element.setAttribute("src", fileName)
    }
    if(element) {
      element.setAttribute('async', '')
      element.setAttribute('defer', '')
      element.addEventListener('load', function() {
                resolve(element)
                console.log('load script resolved')
            }, false)
      element.addEventListener('error', function() {
                reject(element)
                console.log('load script rejected')
            }, false)
      document.body.appendChild(element)
    }
  })
}

export function getFileName(fileName) {
  let pos = fileName.indexOf('?')
  if(pos == -1) {
    let pos2 = fileName.lastIndexOf('/')
    if(pos2 == -1) {
      return fileName
    } else {
      return fileName.substring(pos2 + 1)
    }
  } else {
    if(pos2 == -1) {
      return fileName
    } else {
      return fileName.substring(pos2 + 1, pos)
    }
  }
}
